﻿using AutoMapper;
using B.S.AuthCenter.Api.Write.Application.Command.Users;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.AuthCenter.Api.Write.Application.Handler.Users
{
    public class AddUsersHandler : IRequestHandler<AddUsersCommand, ApiResult<int>>
    {
        IBaseRepository<UserModel> UserRepo;
       
        IMapper mapper;
        IBaseRepository<LogModel> logRepo;

        public AddUsersHandler(IBaseRepository<UserModel> userRepo, IMapper mapper, IBaseRepository<LogModel> logRepo)
        {
            UserRepo = userRepo;
            this.mapper = mapper;
            this.logRepo = logRepo;
        }

        public Task<ApiResult<int>> Handle(AddUsersCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();
            var users=UserRepo.GetAll().Where(c=>c.UserName==request.UserName).Count();
            if (users > 0)
            {
               
                res.Msg = "用户名不能重复";
                res.Code=ApiEnum.Error;
                return Task.FromResult(res);
            }
            var model=mapper.Map<UserModel>(request);
            model.Creator = request.UserName;
            model.CreatorDate = DateTime.Now;
            LogModel logModel=new LogModel()
            {
                LogContent="账号添加",
                Creator=request.UserName,
                CreatorDate=DateTime.Now,
            };
            int a = 0;
            int b = 0;
            using (var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                a= UserRepo.Add(model).Result;
                b = logRepo.Add(logModel).Result;
                tran.Complete();
            }
                if (a > 0)
                {
                    
                    res.Code = ApiEnum.Success;
                    res.Msg = "添加用户信息成功";
                    res.Datas = a;
                    return Task.FromResult(res);
                }
                else
                {
                   
                    res.Code = ApiEnum.Fail;
                    res.Msg = "添加用户信息失败";
                    res.Datas = a;
                    return Task.FromResult(res);
                }
        }
    }
}
